//@Time:2022/4/2 15:44
//@Author:aFun

package indi.csms_springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import indi.csms_springboot.domain.*;
import indi.csms_springboot.mapper.*;
import indi.csms_springboot.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@Service
public class ManagerServiceImpl implements ManagerService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    ManagerMapper managerMapper;
    @Autowired
    TeacherMapper teacherMapper;
    @Autowired
    StudentMapper studentMapper;
    @Autowired
    OfficerMapper officerMapper;

    @Override
    @Transactional
    public boolean addUser(User user) {
        // 使用MD5进行加密
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            BASE64Encoder base64Encoder = new BASE64Encoder();
            // 密码可以为空，默认为123456
            String psd = user.getPassword().equals("") ? "123456" : user.getPassword();
            String finalPsd = base64Encoder.encode(md5.digest(psd.getBytes("utf-8")));
            user.setPassword(finalPsd);

            // 数据库操作
            // 先添加用户到user表中
            int i = userMapper.insert(user);
            // 再在相应角色的表中添加数据
            int j=0;
            switch (user.getRoleId()){
                case 1:
                    j=i;
                    break;
                case 2:
                    j = officerMapper.insert(new Officer(null, user.getAccount()));
                    break;
                case 3:
                    j=teacherMapper.insert(new Teacher(null,user.getAccount()));
                    break;
                case 4:
                    j=studentMapper.insert(new Student(null,user.getAccount()));
                    break;
                default:
                    break;
            }
            if(i<=0||j<=0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    public List<User> findAll() {
        List<User> users = userMapper.selectList(null);
        return users;
    }

    @Override
    public boolean updateUser(User user) {
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("uid",user.getUid());
        int update = userMapper.update(user,wrapper);
        return update>0;
    }

    @Override
    @Transactional
    public boolean deleteUserById(Integer uid) {
        User user = findUserById(uid);
        int j=0;
        switch (user.getRoleId()){
            case 1:
                j=1;
                break;
            case 2:
                QueryWrapper<Officer> wrapperO=new QueryWrapper<>();
                wrapperO.eq("account",user.getAccount());
                j= officerMapper.delete(wrapperO);
                break;
            case 3:
                QueryWrapper<Teacher> wrapperT=new QueryWrapper<>();
                wrapperT.eq("account",user.getAccount());
                j= teacherMapper.delete(wrapperT);
                break;
            case 4:
                QueryWrapper<Student> wrapperS=new QueryWrapper<>();
                wrapperS.eq("account",user.getAccount());
                j= studentMapper.delete(wrapperS);
                break;
            default:
                break;
        }
        int i = userMapper.deleteById(uid);
        if(i<=0||j<=0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }

    @Override
    public User findUserById(Integer uid) {
        User user = userMapper.selectById(uid);
        return user;
    }

    @Override
    public boolean delSelectedUser(String[] ids) {
        for (String id : ids) {
            int i = Integer.parseInt(id);
            boolean b = deleteUserById(i);
            if(!b){
                return false;
            }
        }
        return true;
    }

    @Override
    public IPage<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) {
        int currentPage = Integer.parseInt(_currentPage);
        int rows = Integer.parseInt(_rows);

        Page<User> page=new Page<>(currentPage,rows);
        QueryWrapper<User> wrapper=new QueryWrapper<>();

        Set<String> keySet = condition.keySet();
        for (String key : keySet) {
            if ("currentPage".equals(key) || "rows".equals(key)) {
                continue;
            }
            String value = condition.get(key)[0];
            if (value != null && !"".equals(value)) {
                wrapper.like(key,value);
            }
        }

        IPage<User> userIPage = userMapper.selectPage(page, wrapper);
        return userIPage;

    }
}
